<template>
  <div id="shopCartBox">
    <navTop></navTop>
    <div class="shopCart_null" v-show="!showCart">
      <div class="shopCart_null_pic">
        <img src="../assets/image/cart/null-car.png" alt />
      </div>
      <span>我的收藏</span>
      <span @click="goShopping">去逛逛</span>
      <foot></foot>
    </div>

    <div class="shopCart_normal" v-show="showCart">
      <div class="shopCart-warp">
        <div class="shopTools">
          <span>在售商品</span>
          <p>
            <label>
              <input type="checkbox" v-model="chooseAll" />
              <span>{{chooseAll ? "全不选" : "全选"}}</span>
            </label>
            <input :class="{nullColor:!isDel}" @click="delConfirm" type="button" value="删除" />
          </p>
        </div>

        <ul class="goodsList">
          <li v-for="(item,index) in goodsList" :key="index" @click="goGoods(item.gid)">
            <input
              type="checkbox"
              v-model="item.ischeck"
              @click.stop="changecheck(myName,item.gid,index,item.color,item.size)"
            />
            <img :src="item.gimg" alt />
            <h3>
              <p>{{item.gname}}</p>
              <p>颜色：{{item.color}} 尺码：{{item.size}}</p>
              <p>
                <em>￥{{item.gprice}}</em>
                <span @click.stop="reduceCount(item.gid,index,item.gcount,item.color,item.size)">-</span>
                <input type="text" v-model="item.gcount" />
                <span
                  @click.stop="addCount(item.gid,index,item.gcount,item.gstock,item.color,item.size)"
                >+</span>
              </p>
            </h3>
            <i
              class="iconfont icon-shanchu1"
              @click.stop="del(index,myName,item.gid,item.color,item.size)"
            ></i>
          </li>
        </ul>
      </div>
      <div class="shopCart-total">
        <div class="total">
          <p>
            需要支付:
            <span>￥{{parseInt(totalPrice * 0.8)}}</span>
            <em>去领券</em>
          </p>
          <p>
            总金额:
            <span>￥{{totalPrice}}&nbsp;</span>已优惠
            <span>￥{{parseInt(totalPrice * (1 - 0.8))}}</span>
          </p>
        </div>
        <input
          :class="{nullColor:!isDel}"
          @click="adddingdan"
          type="button"
          :value="'结算('+totalCount+')'"
        />
      </div>
    </div>
  </div>
</template>

<script>
import navTop from "@/components/common/navTop";
import foot from "@/components/common/foot";
import cart from "@/api/shopcart";
export default {
  data() {
    return {
      myName: this.$store.state.user.username,
      totalCount: "",
      totalPrice: "",
      showCart: true,
      isDel: true,
      goodsList: [],
      allCheck: ""
    };
  },

  components: {
    navTop,
    foot
  },
  created() {
    this.getGoodsCart();
  },
  methods: {
    goGoods(gid) {
      this.$router.push("/goodsDetails/" + gid);
    },
    adddingdan() {
      this.$dialog
        .confirm({
          message: "确定进行结算?"
        })
        .then(async () => {
          let myAddress = this.$store.state.user.address;
          if (myAddress) {
            try {
              let p = await cart.addDingdan(this.$store.state.user.username);
              if (p.data.flag) {
                this.delPart();
              }
            } catch (err) {
              this.$toast.fail(err + "");
            }
          } else {
            this.$toast.fail("请添加地址信息后进行结算");
            setTimeout(() => {
              this.$router.push("/my/logOut");
            }, 1500);
          }
        })
        .catch(() => {});
    },
    async changecheck(username, gid, index, color, size) {
      try {
        let newcheck = !this.goodsList[index].ischeck;
        let p = await cart.changeCheck(username, gid, newcheck, color, size);
      } catch (err) {
        this.$toast.fail(err + "");
      }
    },
    async changeallcheck(username, newcheck) {
      try {
        let p = await cart.changeAllCheck(username, newcheck);
      } catch (err) {
        this.$toast.fail(err + "");
      }
    },
    async getGoodsCart() {
      try {
        let p = await this.$store.dispatch(
          "getcart",
          this.$store.state.user.username
        );
        if (p.flag) {
          this.goodsList = p.data;
        }
      } catch (err) {
        this.$toast.fail(err + "");
      }
    },
    goShopping() {
      this.$router.push("/");
    },
    addCount(gid, index, count, stock, color, size) {
      if (count >= stock) {
        return;
      }
      this.goodsList[index].gcount++;
      this.changeCount(
        this.$store.state.user.username,
        gid,
        this.goodsList[index].gcount,
        color,
        size
      );
    },
    reduceCount(gid, index, count, color, size) {
      if (count <= 1) {
        return;
      }
      this.goodsList[index].gcount--;
      this.changeCount(
        this.$store.state.user.username,
        gid,
        this.goodsList[index].gcount,
        color,
        size
      );
    },
    async changeCount(username, gid, gcount, color, size) {
      try {
        let p = await this.$store.dispatch("changecount", {
          username,
          gid,
          gcount,
          color,
          size
        });
      } catch (err) {
        this.$toast.fail(err + "");
      }
    },
    del(index, username, gid, color, size) {
      this.$dialog.confirm({
        message: "确定要删除吗"
      })
        .then(async () => {
           try {
          this.goodsList.splice(index, 1);
          let p = await this.$store.dispatch("delgoods", {
            username,
            gid,
            color,
            size
          });
        } catch (err) {
          this.$toast.fail(err + "");
        }
        })
        .catch(() => {
        });
    },
    delConfirm() {
      this.$dialog.confirm({
         message: '确定要删除吗？',
    })
  .then(() => {
    this.delPart();
    })
  .catch(() => {
    // on cancel
  });
    },
    async delPart() {
      try {
        this.goodsList = this.goodsList.filter(item => item.ischeck == false);
        let p = await this.$store.dispatch("delcheckgoods", this.myName);
      } catch (err) {
        this.$toast.fail(err + "");
      }
    }
  },
  computed: {
    chooseAll: {
      get() {
        return this.goodsList.every(item => item.ischeck);
      },
      set(val) {
        this.goodsList.forEach(item => {
          item.ischeck = val;
        });
      }
    }
  },
  watch: {
    goodsList: {
      deep: true,
      immediate: true,
      handler(newval) {
        if (newval.length > 0) {
          this.showCart = true;
          let totalCount = 0;
          let totalPrice = 0;
          newval.forEach(item => {
            if (item.gcount < 1) {
              item.gcount = 1;
            }
            if (item.gcount >= item.gstock) {
              item.gcount = item.gstock;
            }
            if (item.ischeck) {
              totalCount += parseInt(item.gcount);
              totalPrice += parseInt(item.gcount * item.gprice);
            }
          });
          for (let i = 0; i < newval.length - 1; i++) {
            if (newval[i].ischeck != newval[i + 1].ischeck) {
              this.allCheck = false;
              break;
            }
            this.allCheck = true;
          }
          if (newval.length == 1) {
            this.allCheck = true;
          }
          if (this.allCheck) {
            this.changeallcheck(this.myName, newval[0].ischeck);
          }
          this.totalCount = totalCount;
          this.totalPrice = totalPrice;
          this.isDel = newval.some(item => item.ischeck);
        } else {
          this.showCart = false;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.shopCart_null {
  padding: 20px;
  span {
    display: inline-block;
    width: 48%;
    height: 36px;
    background: #f5f5f5;
    border-radius: 5px;
    line-height: 36px;
    &:nth-of-type(1) {
      margin-right: 4%;
    }
  }
  .shopCart_null_pic {
    width: 100%;
    height: 228px;
    border: 1px solid #d8d8d8;
    position: relative;
    margin-bottom: 10px;
    img {
      width: 144px;
      height: 52px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
    }
  }
}
.shopCart_normal {
  .shopCart-warp {
    padding: 0 20px;
    .shopTools {
      width: 100%;
      height: 30px;
      border-bottom: 1px solid #e9e9e9;
      display: flex;
      justify-content: space-between;
      align-items: center;
      p {
        display: flex;
        justify-content: space-between;
        align-items: center;
        input {
          padding: 2px 4px;
          background: #b71b21;
          border-radius: 4px;
          color: #fff;
        }
        label {
          @extend input;
          margin-right: 10px;
          input {
            display: none;
          }
        }
      }
    }
    .goodsList {
      margin-bottom: 60px;
      li {
        width: 100%;
        height: 100px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ededed;
        input[type="checkbox"] {
          width: 16px;
          height: 16px;
        }
        h3 {
          width: 168px;
          height: 100%;
          font-size: 12px;
          color: #414141;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          text-align: left;
          p {
            &:nth-of-type(1) {
              width: 100%;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            &:nth-of-type(2) {
              color: #8d8d8d;
            }
            input[type="text"] {
              width: 28px;
              height: 28px;
              border-radius: 4px;
              border: 1px solid #dbdbdb;
              text-align: center;
              display: inline-block;
              margin: 0 6px;
              position: relative;
              top: -2px;
            }
            span {
              display: inline-block;
              width: 26px;
              height: 26px;
              background: #f5f5f5;
              font-size: 22px;
              color: #626262;
              text-align: center;
              border-radius: 4px;
              box-shadow: 1px 1px 1px #5c5c5c55;
            }
            em {
              color: #bc2c32;
              font-weight: bold;
              font-size: 14px;
              margin-right: 14px;
            }
          }
        }
        img {
          width: 80px;
          height: 80px;
          border-radius: 10px;
        }
        .iconfont {
          font-size: 22px;
          color: #c8c8c8;
        }
      }
    }
  }
  .shopCart-total {
    width: 100%;
    height: 48px;
    background: #f5f5f5;
    border-top: 1px solid #c8c8c8;
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    font-size: 12px;
    letter-spacing: 0.1em;
    input[type="button"] {
      width: 102px;
      height: 38px;
      background: #b81c22;
      text-align: center;
      line-height: 38px;
      font-size: 16px;
      color: #fff;
      font-weight: bold;
      letter-spacing: 0.2em;
    }
    .total {
      p {
        text-align: left;
      }
      p:nth-of-type(1) {
        span {
          color: #b51218;
          margin-right: 10px;
        }
        em {
          display: inline-block;
          width: 64px;
          height: 16px;
          background: #b51218;
          color: #fff;
          text-align: center;
          position: relative;
          &::after {
            content: "";
            display: block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            position: absolute;
            background: #f5f5f5;
            left: -6px;
            top: 3px;
          }
          &::before {
            content: "";
            display: block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            position: absolute;
            background: #f5f5f5;
            right: -6px;
            top: 3px;
          }
        }
      }
    }
  }
}
.nullColor {
  background: rgb(178, 178, 178) !important;
}
</style>